package com.mynet.okhttp.callback;

import android.util.Log;

import com.mynet.okhttp.DownloadFile;
import com.mynet.okhttp.listener.OkFileLisener;
import com.mynet.okhttp.listener.OkListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by xiatian on 16/11/18.
 */

public class DownloadCallBack extends CommonCallback {

    private DownloadFile mDownloadFile;
    private OkFileLisener mOkFileLisener;

    public DownloadCallBack(DownloadFile downloadFile, OkFileLisener okFileLisener, OkListener listener) {
        super(listener);
        this.mDownloadFile = downloadFile;
        this.mOkFileLisener = okFileLisener;
    }

    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        InputStream is = response.body().byteStream();
        final long totalBytes = response.body().contentLength();
        long writedBytes = 0;
        int len = 0;
        File file = new File(mDownloadFile.getFilePath());
        byte[] buf = new byte[1024];
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (Exception e) {
            Log.i("hh",e.getMessage());
        }
        while ((len = is.read(buf)) != -1) {
            fos.write(buf, 0, len);
            writedBytes += len;
            final long finalWritedBytes = writedBytes;
            mDelieverHandler.post(new Runnable() {
                @Override
                public void run() {
                    mOkFileLisener.progress(finalWritedBytes, totalBytes);
                }
            });
        }
        mDelieverHandler.post(new Runnable() {
            @Override
            public void run() {
                mListener.onSuccess("Success", response.code(), response.headers());
            }
        });
        fos.flush();
        fos.close();
        is.close();
    }
}
